<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :inline="true" :model="queryParams" class="demo-form-inline">
      <el-form-item label="数据库名称" prop="databaseName">
        <el-input
          v-model="queryParams.databaseName"
          placeholder="请输入数据库名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="small" :disabled="single" @click="handleUpdate">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="small" :disabled="multiple" @click="handleDelete">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-download" size="small" @click="handleExport">
          导出
        </el-button>
      </el-col>
    </el-row>

    <!-- 表格展示区域 -->
    <el-table
      v-loading="loading"
      :data="databaseList"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品ID" align="center" prop="id" />
      <el-table-column label="数据库名称" align="center" prop="databaseName" />
      <el-table-column label="图标" align="center" prop="icon">
        <template slot-scope="scope">
          <img v-if="scope.row.icon" :src="scope.row.icon" style="width: 40px; height: 40px;" />
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="type" />
      <el-table-column label="数据库描述" align="center" prop="description" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >
            修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="数据库名称" prop="databaseName">
          <el-input v-model="form.databaseName" placeholder="请输入数据库名称" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-input v-model="form.type" placeholder="请输入数据库类型" />
        </el-form-item>
        <el-form-item label="数据库描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入数据库描述" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'WangXin',
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 模拟数据列表
      mockDataList: [
        {
          id: 100,
          databaseName: 'mysql',
          icon: 'https://img.alicdn.com/tfs/TB1HfGJj1uSBuNjSspiXXbugXXa-120-120.png',
          type: '关系型-单机',
          description: 'MySQL是一个关系型数据库管理系统',
          remark: '官方推荐'
        },
        {
          id: 101,
          databaseName: 'postgresql',
          icon: 'https://img.alicdn.com/tfs/TB1Z57qj1uSBuNjSspiXXbugXXa-120-120.png',
          type: '关系型-单机',
          description: 'PostgreSQL是功能强大的开源关系型数据库',
          remark: '企业级支持'
        },
        {
          id: 102,
          databaseName: 'mongodb',
          icon: 'https://img.alicdn.com/tfs/TB1iWJj1uSBuNjSspiXXbugXXa-120-120.png',
          type: '非关系型-文档',
          description: 'MongoDB是基于分布式文件存储的数据库',
          remark: 'NoSQL优选'
        }
      ],
      // 数据库产品表格数据
      databaseList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        databaseName: '',
        type: ''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        databaseName: [
          { required: true, message: '数据库名称不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '类型不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询数据库产品列表 */
    getList() {
      this.loading = true
      // 使用setTimeout模拟网络延迟
      setTimeout(() => {
        // 本地数据过滤
        let filteredList = [...this.mockDataList]
        
        // 按数据库名称过滤
        if (this.queryParams.databaseName) {
          filteredList = filteredList.filter(item => 
            item.databaseName.toLowerCase().includes(this.queryParams.databaseName.toLowerCase())
          )
        }
        
        // 按类型过滤
        if (this.queryParams.type) {
          filteredList = filteredList.filter(item => 
            item.type.toLowerCase().includes(this.queryParams.type.toLowerCase())
          )
        }
        
        // 分页处理
        this.total = filteredList.length
        const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize
        const end = start + this.queryParams.pageSize
        this.databaseList = filteredList.slice(start, end)
        
        this.loading = false
      }, 500)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增数据库产品'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      // 从模拟数据中查找对应ID的记录
      const item = this.mockDataList.find(data => data.id === id)
      if (item) {
        this.form = { ...item }
      } else {
        // 如果找不到，使用默认数据
        this.form = {
          id: id,
          databaseName: 'mysql',
          type: '关系型-单机',
          description: 'MySQL是一个关系型数据库管理系统',
          remark: '官方推荐'
        }
      }
      this.open = true
      this.title = '修改数据库产品'
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // 修改操作
            const index = this.mockDataList.findIndex(item => item.id === this.form.id)
            if (index > -1) {
              // 更新图标
              if (!this.form.icon) {
                this.form.icon = 'https://img.alicdn.com/tfs/TB1HfGJj1uSBuNjSspiXXbugXXa-120-120.png'
              }
              this.mockDataList[index] = { ...this.form }
            }
            this.$message.success('修改成功')
          } else {
            // 新增操作
            const newId = Math.max(...this.mockDataList.map(item => item.id), 0) + 1
            const newItem = {
              ...this.form,
              id: newId,
              icon: this.form.icon || 'https://img.alicdn.com/tfs/TB1HfGJj1uSBuNjSspiXXbugXXa-120-120.png'
            }
            this.mockDataList.push(newItem)
            this.$message.success('新增成功')
          }
          this.open = false
          this.getList()
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm(
        `确定要删除选中的数据库产品吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 从模拟数据中删除
        const idArray = Array.isArray(ids) ? ids : [ids]
        this.mockDataList = this.mockDataList.filter(item => !idArray.includes(item.id))
        this.$message.success('删除成功')
        this.getList()
      }).catch(() => {
        // 取消删除
      })
    },
    /** 导出按钮操作 - 模拟导出 */
    handleExport() {
      this.$message.success('导出功能已触发（模拟）')
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    }
  }
}
</script>